package com.yc.tomcat2;

import com.yc.tomcat2.javax.servlet.YcServletContext;
import com.yc.tomcat2.javax.servlet.http.YcHttpServletRequest;
import com.yc.tomcat2.javax.servlet.http.YcHttpServletResponse;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
 * 任务类
 * @author zwei
 * @create 2024-07-25 21:16
 */
public class TaskService implements Runnable{
    private Logger logger = Logger.getLogger(TaskService.class);
    private Socket s;
    private InputStream iis;
    private OutputStream oos;
    private boolean flag=true;
    public TaskService(Socket s) {
        this.s=s;
        try {
            this.iis=s.getInputStream();
            this.oos=s.getOutputStream();
        } catch (IOException e) {
            logger.error("socket获取流异常");
            e.printStackTrace();
            flag=false;
        }
    }

    @Override
    public void run() {
//        do {
//              //通过socket的InputStream获取请求信息 解析
//              //通过socket的OutputStream发送响应信息
//        }while ()
        if (this.flag){
//            YcHttpServletRequest req=new YcHttpServletRequest(this.s,this.iis);
//            YcHttpServletResponse resp=new YcHttpServletResponse(req,this.oos);
//            resp.send();
            YcHttpServletRequest request=new YcHttpServletRequest(this.s,this.iis);
            YcHttpServletResponse response=new YcHttpServletResponse(request,this.oos);
            //根据 request中的requestURI来判断资源
            Processor processor=null;
            int contentPathLength=request.getContextPath().length();
            String uri=request.getRequestURI();
            if (YcServletContext.servletClass.containsKey(uri)){
                //这是动态请求
                processor=new DynamicProcessor();
            }else {
                //这是静态请求
                processor=new StaticProcessor();
            }
            try {
                processor.process(request,response);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            this.iis.close();
            this.oos.close();
            this.s.close();
        } catch (IOException e) {
            logger.error("socket关闭异常");
            e.printStackTrace();
        }
    }
}
